package com.since.algorithm.sort;

import java.util.Arrays;

/**
 * Created by Sincerity on 2020/5/15.
 * 描述：归并排序
 * {@link #mergeSort(int[], int, int, int[])} 归并
 */
class MergeSort {
    public static void main(String[] args) {
        int[] array = {8, 4, 5, 7, 1, 3, 6, 2};
        int[] temp = new int[array.length];
        System.out.println("原数组:" + Arrays.toString(array));
        mergeSort(array, 0, array.length - 1, temp);
        System.out.println("排序后:" + Arrays.toString(array));
    }

    /**
     * 拆分数组
     *
     * @param arr   目标数组
     * @param left  左边索引
     * @param right 右边索引
     * @param temp  临时数组
     */
    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2; //中间索引
            //向左递归进行分解
            mergeSort(arr, left, mid, temp);
            //向右递归进行分解
            mergeSort(arr, mid + 1, right, temp);
            //合并
            merge(arr, left, mid, right, temp);

        }
    }

    /**
     * 合并方法
     *
     * @param array 目标数组
     * @param left  左边的索引
     * @param mid   中间索引
     * @param right 右边索引
     * @param temp  临时存放的数组
     */
    public static void merge(int[] array, int left, int mid, int right, int[] temp) {
        int i = left, j = mid + 1, t = 0;
        while (i <= mid && j <= right) {
            //右边组的数大于左边的分组数
            if (array[i] <= array[j]) {
                temp[t] = array[i];
                t += 1;
                i += 1;
            } else {
                temp[t] = array[j];
                t += 1;
                j += 1;
            }
        }
        //把剩余的元素一次添加到temp数组中
        while (i <= mid) {
            temp[t] = array[i];
            t += 1;
            i += 1;
        }
        while (j <= right) {
            temp[t] = array[j];
            t += 1;
            j += 1;
        }
        t = 0;
        int tempLeft = left;
        while (tempLeft <= right) {
            array[tempLeft] = temp[t];
            t += 1;
            tempLeft += 1;
        }
    }
}
